package cn.stronglink.assetmanage.business.inventory.view;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.stronglink.assetmanage.BaseActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inventory.adapter.InventoryListAdapter;
import cn.stronglink.assetmanage.business.inventory.adapter.InventoryListWaitAdapter;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.InventoryDao;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.InventoryDetail;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.listener.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.InventoryDataUtil;
import cn.stronglink.assetmanage.utils.dao.PatrolDataUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.netrequest.business.inventory.InventoryService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class InventoryActivity extends BaseActivity implements View.OnClickListener, onRecyclerListener,
        View.OnTouchListener {


    private Button btn_inventory_already;
    private Button btn_inventory_wait;
    private RecyclerView inventory_list;
    private TextView tv_inventory_createOrExecute_time;
    private TextView tv_inventory_createOrExecute_person;
    private TextView tv_inventory_finishOrExecute_time;
    private TextView tv_inventory_uploadOrExecutePerson;
    private SwipeRefreshLayout sfl_inventory_order;
    private Dialog dialog;
    private InventoryListAdapter inventoryListAdapter;
    private InventoryListWaitAdapter inventoryListWaitAdapter;
    private LinearLayoutManager layoutManager;

    private List<Inventory> inventoryList = new ArrayList<>();  //盘点单列表

    private List<Inventory> wait_inventorylist = new ArrayList<>(); //待盘点单列表
    private List<Inventory> already_inventorylist = new ArrayList<>();  //已盘点单列表
    private int waitnum = 0;    //待盘点数量
    private int alreadynum = 0; //已盘点数量
    private int status = 0; //默认显示待盘点

    private InventoryService inventoryService;
    private float mPosX, mCurPosX;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventory);
        initView();
        initData();
    }


    @Override
    protected void onResume() {
        super.onResume();
        setSelectPosition(2);
        initData();
        changeColor(0);
    }

    private void initView() {
        btn_inventory_wait = findViewById(R.id.btn_inventory_wait);
        btn_inventory_already = findViewById(R.id.btn_inventory_already);
        inventory_list = findViewById(R.id.inventory_list);
        tv_inventory_createOrExecute_time = findViewById(R.id.tv_inventory_createOrExecute_time);
        tv_inventory_createOrExecute_person = findViewById(R.id.tv_inventory_createOrExecute_person);
        tv_inventory_finishOrExecute_time = findViewById(R.id.tv_inventory_finishOrExecute_time);
        tv_inventory_uploadOrExecutePerson = findViewById(R.id.tv_inventory_uploadOrExecutePerson);
        sfl_inventory_order = findViewById(R.id.sfl_inventory_order);
        inventoryService = new InventoryService();

        sfl_inventory_order.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshInventoryData();
            }
        });

        btn_inventory_already.setOnClickListener(this);
        btn_inventory_wait.setOnClickListener(this);

        inventoryListAdapter = new InventoryListAdapter(this, null);
        inventoryListWaitAdapter = new InventoryListWaitAdapter(this, null);
        layoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        inventory_list.setLayoutManager(layoutManager);
        //默认第一次加载为待盘点单
        inventoryListWaitAdapter.setListener(this);
        inventory_list.setAdapter(inventoryListWaitAdapter);
        inventory_list.setOnTouchListener(this);
    }

    private void initData() {
        //获取盘点单
        showInventoryData();
        //默认为待盘点选中
        btn_inventory_wait.setClickable(true);
        changeColor(status);
        changeText();
        refreshWaitList(wait_inventorylist);
    }


    private void showInventoryData() {
        inventoryList = InventoryDataUtil.getInventory();
        wait_inventorylist.clear();
        already_inventorylist.clear();
        //判断是已盘点还是未盘点
        for (Inventory inventorys : inventoryList) {
            if (inventorys.getStatus() == 0) {
                wait_inventorylist.add(inventorys);
            } else {
                already_inventorylist.add(inventorys);
            }
        }
        waitnum = wait_inventorylist.size();
        alreadynum = already_inventorylist.size();
    }

    /**
     * 刷新数据
     */
    private void refreshInventoryData() {
        //判断是离线还是在线
        SyncTypes syncTypes = DaoManager.getDaoSession(this).getSyncTypesDao().
                queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp = Constants.STATUS_TWO;
        if (syncTypes != null) {
            tp = syncTypes.getSyscTs();
        }
        switch (tp) {
            case Constants.STATUS_ONE:
                //自动
                getInventoryService();
                break;
            case Constants.STATUS_TWO:
                //离线，从数据库拿数据
                showInventoryData();
                stopRefresh();
                refreshWaitList(wait_inventorylist);
                ToastUtil.toastShort("本地数据加载完成");
                break;
            default:
                stopRefresh();
                break;
        }
    }

    private void getInventoryService() {
        if (inventoryService != null) {
            try {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String result = null;
                        try {
                            result = inventoryService.downloadInventoryWorkOrder(User.getInstance().getId_());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        saveInventoryData(result);
                    }
                }).start();
            } catch (Exception e) {
                e.printStackTrace();
                stopRefresh();
            }
        }
    }

    private void saveInventoryData(String resultJson) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                stopRefresh();
            }
        });
        Result<List<Inventory>> inventoryResult = null;
        Gson gson = new Gson();
        inventoryResult = gson.fromJson(resultJson, new TypeToken<Result<List<Inventory>>>() {
        }.getType());
        if (inventoryResult != null && inventoryResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
            if (inventoryResult.getData() != null) {
                List<Inventory> inventoryList = inventoryResult.getData();
                // 验收单列表
                if (inventoryList != null && inventoryList.size() > 0) {
                    //从服务器获取盘点数据，清除本地盘点数据库表
                    for (Inventory inventory : inventoryList) {
                        // 如果盘点单存在，就不添加
                        Inventory tempInventory = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().queryBuilder().where(
                                InventoryDao.Properties.Id_.eq(inventory.getId_())
                        ).unique();
                        if (tempInventory != null) {
                            continue;
                        }
                        inventory.setOrderType(Constants.STATUS_TWO);
                        inventory.setStatus(0);
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().insertOrReplace(inventory);
                        InventoryDataUtil.saveInventoryDetailList(inventory.getDetailList(),inventory);
                        InventoryDataUtil.saveInventoryDetailList(inventory.getMoreOutList(),inventory);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.toastShort("更新完成");
                            initData();
                        }
                    });

                } else {
                    ToastUtil.toastShort("更新完成");
                }
            } else {
                ToastUtil.toastShort("更新完成");
            }
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.toastShort("更新失败");
                }
            });

        }
    }

    /**
     * 停止刷新
     */
    private void stopRefresh() {
        if (sfl_inventory_order != null) {
            sfl_inventory_order.setRefreshing(false);
        }
    }

    //改变button的text
    private void changeText() {
        btn_inventory_wait.setText("待盘点(" + waitnum + ")");
        btn_inventory_already.setText("已盘点(" + alreadynum + ")");

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_inventory_already:
                refreshAlreadyList(already_inventorylist);
                status = 1;
                changeColor(status);
                break;
            case R.id.btn_inventory_wait:
                refreshWaitList(wait_inventorylist);
                status = 0;
                changeColor(status);
                break;
            default:
                break;
        }
    }

    //刷新列表
    private void refreshWaitList(List<Inventory> inventoryList) {
        inventoryListWaitAdapter.setListener(this);
        inventory_list.setAdapter(inventoryListWaitAdapter);
        inventoryListWaitAdapter.notifyDatasChanged(inventoryList);
    }

    //刷新列表
    private void refreshAlreadyList(List<Inventory> inventoryList) {
        inventoryListAdapter.setListener(this);
        inventory_list.setAdapter(inventoryListAdapter);
        inventoryListAdapter.notifyDatasChanged(inventoryList);
    }

    //改变待盘点已盘点颜色和显示的text信息
    private void changeColor(int status) {
        if (status == 0) {
            btn_inventory_wait.setBackground(null);
            btn_inventory_wait.setTextColor(getResources().getColor(R.color.blue_inventory_text));
            btn_inventory_already.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
            btn_inventory_already.setTextColor(Color.BLACK);

            tv_inventory_createOrExecute_time.setText("创建时间");
            tv_inventory_createOrExecute_person.setText("创建人");
            tv_inventory_finishOrExecute_time.setText("计划执行时间");
            tv_inventory_uploadOrExecutePerson.setText("执行人");
        } else {
            btn_inventory_already.setBackground(null);
            btn_inventory_already.setTextColor(getResources().getColor(R.color.blue_inventory_text));
            btn_inventory_wait.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
            btn_inventory_wait.setTextColor(Color.BLACK);
            tv_inventory_createOrExecute_time.setText("计划执行时间");
            tv_inventory_createOrExecute_person.setText("执行人");
            tv_inventory_finishOrExecute_time.setText("完成时间");
            tv_inventory_uploadOrExecutePerson.setText("上传状态");
        }

    }


    @Override
    public void onItemClicked(View v, int postion) {
        dialog = CustomProgressDialog.createLoadingDialog(this, "正在加载中...");
        dialog.setCancelable(false);
        dialog.show();
        //进入详情页面
        Inventory inventory = new Inventory();
        if (status == 1) {
            inventory = already_inventorylist.get(postion);
        } else {
            inventory = wait_inventorylist.get(postion);
        }
        Intent intent = new Intent(this, InventoryDetailActivity.class);
        String inventory_id = inventory.getId_() + "";
        intent.putExtra("inventoryDetail", inventory_id);
        startActivity(intent);
        if (dialog != null) {
            dialog.cancel();
        }
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPosX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                mCurPosX = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                if (mCurPosX - mPosX > 0
                        && (Math.abs(mCurPosX - mPosX) > Constants.FLUSH_DISTANCE)) {
                    //向左滑動，显示待盘点
                    if (status != 0) {
                        refreshWaitList(wait_inventorylist);
                        status = 0;
                        changeColor(status);
                    }
                    return true;
                } else if (mCurPosX - mPosX < 0
                        && (Math.abs(mCurPosX - mPosX) > Constants.FLUSH_DISTANCE)) {
                    //向右滑动，显示已盘点
                    if (status != 1) {
                        refreshAlreadyList(already_inventorylist);
                        status = 1;
                        changeColor(status);
                    }
                    return true;
                }
                break;
            default:
                break;
        }

        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            dialog.cancel();
        }
    }
}
